package com.cndongtai.service.light;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cndongtai.constant.LightConstant;
import com.cndongtai.dao.impl.DtuDao;
import com.cndongtai.dao.impl.LightDao;
import com.cndongtai.map.GDMapServer;
import com.cndongtai.net.NetController;
import com.cndongtai.net.SocketContainer;
import com.cndongtai.net.redis.RedisServer;
import com.cndongtai.po.Dtu;
import com.cndongtai.po.Light;

@Service("dtuService")
public class DtuService {
	
	@Resource(name="dtuDao")
	private DtuDao dtuDao;
	
	@Resource(name="lightDao")
	private LightDao lightDao;
	
	private GDMapServer mapServer = new GDMapServer();
	
	private RedisServer redis = RedisServer.getInstance();
	
	public Object[] addDtu(String dtuName, String panId, Double longitude,Double latitude,Long createBy,Integer dtuType) {
		Object[] result = new Object[2];
		// 判断panId是否已经存在
		Dtu temp = dtuDao.queryDtuByPanId(panId);
		if(temp!=null) {
			result[0] = false;
			result[1] = "dtu.add.msg.exist";
			return result;
		}
		
		Dtu dtu = new Dtu();
		dtu.setDtuName(dtuName);
		dtu.setPanId(panId.toUpperCase());
		dtu.setLongitude(longitude);
		dtu.setLatitude(latitude);
		dtu.setDtuType(dtuType);
		// 根据经纬度获取地址
		String addressName = mapServer.queryAddressByLatAndLng(latitude.toString(), longitude.toString());
		if(addressName==null || "".equals(addressName)) {
			result[0] = false;
			result[1] = "dtu.add.msg.lnglaterror";
			return result;
		}
		dtu.setAddressName(addressName);
		dtu.setLightState(0);
		dtu.setState(0);
		dtu.setOnlineState(1);
		dtu.setCreateBy(createBy);
		
		if(dtuDao.addDtu(dtu)) {
			result[0] = true;
			result[1] = "dtu.add.msg.success";
		}else {
			result[0] = false;
			result[1] = "dtu.add.msg.fail";
		}
		
		return result;
	}
	
	public Object[] updateDtuLocation(String panId, Double longitude,Double latitude) {
		Object[] result = new Object[2];
		// 判断panId是否已经存在
		Dtu temp = dtuDao.queryDtuByPanId(panId);
		if(temp==null) {
			result[0] = false;
			result[1] = "panId ["+panId+"]设备不存在，请先添加该设备。";
			return result;
		}
		
		Dtu dtu = new Dtu();
		dtu.setDtuId(temp.getDtuId());
		dtu.setLongitude(longitude);
		dtu.setLatitude(latitude);
		
		String[] location = mapServer.locationTransfer(longitude.toString(), latitude.toString());
		// 根据经纬度获取地址
		String addressName = mapServer.queryAddressByLatAndLng(location[1], location[0]);
		if(addressName==null || "".equals(addressName)) {
			result[0] = false;
			result[1] = "请检查您的网络及定位，重新尝试！";
			return result;
		}
		dtu.setAddressName(addressName);
		
		if(dtuDao.updateDtuLocation(dtu)) {
			result[0] = true;
			result[1] = "集中器位置更新成功！";
		}else {
			result[0] = false;
			result[1] = "集中器位置更新失败！";
		}
		
		return result;
	}
	
	public Object[] updateDtuLocationById(Integer dtuId, String longitude,String latitude) {
		Object[] result = new Object[2];
		// 判断panId是否已经存在
		Dtu temp = dtuDao.queryDtuById(dtuId);
		if(temp==null) {
			result[0] = false;
			result[1] = "该设备不存在。";
			return result;
		}
		
		Dtu dtu = new Dtu();
		dtu.setDtuId(temp.getDtuId());
		dtu.setLongitude(Double.valueOf(longitude));
		dtu.setLatitude(Double.valueOf(latitude));
		
		// 根据经纬度获取地址
		String addressName = mapServer.queryAddressByLatAndLng(latitude, longitude);
		if(addressName==null || "".equals(addressName)) {
			result[0] = false;
			result[1] = "请检查您的网络及定位，重新尝试！";
			return result;
		}
		dtu.setAddressName(addressName);
		
		if(dtuDao.updateDtuLocation(dtu)) {
			result[0] = true;
			result[1] = "集中器位置更新成功！";
		}else {
			result[0] = false;
			result[1] = "集中器位置更新失败！";
		}
		
		return result;
	}
	
	public String getDeviceJsonTree(Long userId,String lightOn,String lightDown,String online,String offline) {
		StringBuffer jsonTree = new StringBuffer();
		
		jsonTree.append("[");
		List<Dtu> dtuList = dtuDao.queryDtuListByUserId(userId);
		
		for(Dtu dtu : dtuList) {
			jsonTree.append("{id:'dtu_").append(dtu.getDtuId()).append("',order:1,isLeaf:false,dataObject:{devNum:'").append(dtu.getPanId())
			.append("',addressName:'").append(dtu.getAddressName()).append("',state:'").append(dtu.getLightState()).append("'")
			.append(",dtuType:'").append(dtu.getDtuType()).append("'");
			
			if(dtu.getLightState()==0) {
				jsonTree.append(",stateVal:'").append(lightDown).append("'");
			}else {
				jsonTree.append(",stateVal:'").append(lightOn).append("'");
			}
			
			if(dtu.getDtuType()==0) {
				SocketContainer container = NetController.getSocketPool().get(dtu.getPanId());
				if(container==null) {
					jsonTree.append(",onlinestate:'").append(offline).append("'}");
				}else {
					jsonTree.append(",onlinestate:'").append(online).append("'}");
				}
			}else {
				jsonTree.append(",onlinestate:''}");
			}
			
			
			jsonTree.append(",userObject:{isGroup:true}},");
			
			List<Light> lightList = lightDao.queryLightListByDtuId(dtu.getDtuId());
			for(Light light : lightList) {
				jsonTree.append("{id:'").append(light.getLightId()).append("',pid:'dtu_").append(dtu.getDtuId()).append("',dataObject:{devNum:'").append(light.getLightNum())
				.append("',addressName:'").append(light.getAddressName()).append("',state:'").append(light.getLightState()).append("'");
				
				if(redis.get(LightConstant.REDIS_LIGHT_KEY+dtu.getPanId()+"_"+light.getLightNum())==null) {
					jsonTree.append(",onlinestate:'").append(offline).append("'");
				}else {
					jsonTree.append(",onlinestate:'").append(online).append("'");
				}
				
				if(light.getLightState()==0) {
					jsonTree.append(",stateVal:'").append(lightDown).append("'}},");
				}else {
					jsonTree.append(",stateVal:'").append(lightOn).append("'}},");
				}
			}
		}
		
		if(jsonTree.length()>1) {
			jsonTree.deleteCharAt(jsonTree.length()-1);
		}
		
		jsonTree.append("]");
		
		return jsonTree.toString();
	}
	
	public String getDeviceJsonTree(String lightOn,String lightDown,String online,String offline) {
		StringBuffer jsonTree = new StringBuffer();
		
		jsonTree.append("[");
		List<Dtu> dtuList = dtuDao.queryDtuList();
		
		for(Dtu dtu : dtuList) {
			jsonTree.append("{id:'dtu_").append(dtu.getDtuId()).append("',order:1,isLeaf:false,dataObject:{devNum:'").append(dtu.getPanId())
			.append("',addressName:'").append(dtu.getAddressName()).append("',state:'").append(dtu.getLightState()).append("'")
			.append(",dtuType:'").append(dtu.getDtuType()).append("'");
			
			if(dtu.getDtuType()==0) {
				SocketContainer container = NetController.getSocketPool().get(dtu.getPanId());
				if(container==null) {
					jsonTree.append(",onlinestate:'").append(offline).append("'}");
				}else {
					jsonTree.append(",onlinestate:'").append(online).append("'}");
				}
			}else {
				jsonTree.append(",onlinestate:''}");
			}
			
			jsonTree.append(",userObject:{isGroup:true}},");
			
			List<Light> lightList = lightDao.queryLightListByDtuId(dtu.getDtuId());
			for(Light light : lightList) {
				jsonTree.append("{id:'").append(light.getLightId()).append("',pid:'dtu_").append(dtu.getDtuId()).append("',dataObject:{devNum:'").append(light.getLightNum())
				.append("',addressName:'").append(light.getAddressName()).append("',state:'").append(light.getLightState()).append("'");
				
				if(redis.get(LightConstant.REDIS_LIGHT_KEY+dtu.getPanId()+"_"+light.getLightNum())==null) {
					jsonTree.append(",onlinestate:'").append(offline).append("'");
				}else {
					jsonTree.append(",onlinestate:'").append(online).append("'");
				}
				
				if(light.getLightState()==0) {
					jsonTree.append(",stateVal:'").append(lightDown).append("'}},");
				}else {
					jsonTree.append(",stateVal:'").append(lightOn).append("'}},");
				}
			}
		}
		
		if(jsonTree.length()>1) {
			jsonTree.deleteCharAt(jsonTree.length()-1);
		}
		
		jsonTree.append("]");
		
		return jsonTree.toString();
	}
	
	public boolean delDtu(String dtuId) {
		return dtuDao.delDtu(Integer.valueOf(dtuId));
	}
	
	public Dtu queryDtuById(String dtuId) {
		return dtuDao.queryDtuById(Integer.valueOf(dtuId));
	}
	
	public Dtu queryDtuByPanId(String panId) {
		return dtuDao.queryDtuByPanId(panId);
	}
	
	public boolean changePanId(Long dtuId, String panId) {
		return dtuDao.changePanId(dtuId, panId);
	}
	
	public boolean changeLightState(Long dtuId, Integer lightState) {
		int res = dtuDao.changeLightState(dtuId, lightState);
		if(res>0) {
			return true;
		}
		
		return false;
	}
	
	public List<Dtu> queryDtuList() {
		return dtuDao.queryDtuList();
	}
	
	public List<Dtu> queryDtuListByUserId(Long userId) {
		return dtuDao.queryDtuListByUserId(userId);
	}

}
